/*
 * my_timer.c
 *
 *  Created on: Mar 15, 2021
 *      Author: xrj
 */

#include "stm32f1xx_hal.h"
#include "stm32f1xx_hal_exti.h"
#include "my_timer.h"
#include <time.h>

extern RTC_HandleTypeDef hrtc;


void RTC2tm(RTC_DateTypeDef* sDate, RTC_TimeTypeDef* sTime, struct tm *tm)
{
	tm->tm_year = sDate->Year;
	tm->tm_mon = sDate->Month;
	tm->tm_mday = sDate->Date;
	tm->tm_hour = sTime->Hours;
	tm->tm_min = sTime->Minutes;
	tm->tm_sec = sTime->Seconds;
}

void tm2RTC(struct tm *tm, RTC_DateTypeDef* sDate, RTC_TimeTypeDef* sTime)
{
	sDate->Year = tm->tm_year;
	sDate->Month = tm->tm_mon;
	sDate->Date = tm->tm_mday;
	sTime->Hours = tm->tm_hour;
	sTime->Minutes = tm->tm_min;
	sTime->Seconds = tm->tm_sec;
}

void STOP_sec(uint32_t sec)
{
	RTC_TimeTypeDef sTime;
	RTC_DateTypeDef sDate;
	RTC_AlarmTypeDef sAlarm;
	struct tm tm;
	HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
	HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
	RTC2tm(&sDate, &sTime, &tm);
	time_t t=mktime(&tm)+sec;
	tm2RTC(gmtime(&t), &sDate, &sTime);
	sAlarm.AlarmTime = sTime;
	sAlarm.Alarm = 1;
	__HAL_RTC_ALARM_EXTI_CLEAR_FLAG();
	HAL_RTC_WaitForSynchro(&hrtc);
	HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN);
	HAL_RTC_WaitForSynchro(&hrtc);
	HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_STOPENTRY_WFI);
	//HAL_PWR_EnterSTANDBYMode(); //failed, only valid for first entry
}
